﻿using System;
using System.Windows;
using System.Windows.Documents;
using DiagramDesigner.Common.Controls;
using System.Windows.Interactivity;

namespace Behavior.Rotate
{
    public class RotateBehavior : Behavior<DesignerItem>
    {

        public static readonly DependencyProperty RotationEnabledProperty =
            DependencyProperty.RegisterAttached("RotationEnabled", typeof (bool), typeof (RotateBehavior), 
            new PropertyMetadata(default(bool), PropertyChangedCallback));

        private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            bool newValue = (bool) e.NewValue;
            DesignerItem item = dependencyObject as DesignerItem;

            AdornerLayer adornerLayer = null;
            if (newValue)
            {
                adornerLayer = AdornerLayer.GetAdornerLayer(item);
                if (adornerLayer == null) return;
                RotationAdorner selectionAdorner = new RotationAdorner(item);
                AdornerLayer.GetAdornerLayer(item).Add(selectionAdorner);
            }
            else
            {
                adornerLayer = AdornerLayer.GetAdornerLayer(item);
                if (adornerLayer == null) return;
                Adorner[] adorners = adornerLayer.GetAdorners(item);
                if (adorners != null)
                {
                    foreach (Adorner adorner in adorners)
                    {
                        if (adorner.GetType() == typeof(RotationAdorner))
                        {
                            adornerLayer.Remove(adorner);
                            break;
                        }
                    }
                }
            }
        }

        public static void SetRotationEnabled(UIElement element, bool value)
        {
            element.SetValue(RotationEnabledProperty, value);
        }

        public static bool GetRotationEnabled(UIElement element)
        {
            return (bool) element.GetValue(RotationEnabledProperty);
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            if (AssociatedObject.IsLoaded) 
                RotateBehavior.SetRotationEnabled(AssociatedObject, true);
            
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            SetRotationEnabled(AssociatedObject, false);
        }
    }
}
